package com.wf.userManagement.service.local.impl;

import cn.hutool.core.util.StrUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wf.apicommons.entity.MessageBoard.LeavingAMessage;
import com.wf.apicommons.entity.MessageBoard.MqMessage;
import com.wf.apicommons.entity.userManagement.UserInformation;
import com.wf.apicommons.utils.*;

import com.wf.userManagement.mapper.UserInformationMapper;
import com.wf.userManagement.service.call.MessageBoardFeignService;
import com.wf.userManagement.service.local.UserRelatedService;
import com.wf.userManagement.utils.VerificationCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 用户Service实现类
 */
@Service
public class UserRelatedServiceImpl implements UserRelatedService {
    @Autowired
    private VerificationCodeUtil vcu;
    @Autowired
    private UserInformationMapper uim;
    @Resource
    MessageBoardFeignService messageBoardFeignService;

    @Autowired
    private RedisUtils ru;
    /**
     * 用户注册
     * @param userInfo 用户表单信息
     * @return
     */
    @Override
    public CommonResult<String> userRegister(UserInformation userInfo) {
        String password=userInfo.getPassword();
        String  newCode=userInfo.getCode();
        String  phoneNumber=userInfo.getPhoneNumber();
        if(StrUtil.isNotBlank(password)&&StrUtil.isNotBlank(userInfo.getNickName())&&StrUtil.isNotBlank(phoneNumber)&&StrUtil.isNotBlank(newCode)){
            //判断用户是否重复
            List<UserInformation> userList = uim.selectByMap(new HashMap<String, Object>() {{
                put("nick_name",userInfo.getNickName());
            }});
            //验证昵称是否重复
            if(userList!=null&&userList.size()>0){
                return CommonResult.fail(CodeEnum.DUPLICATE_NICKNAME);
            }

           //验证验证码是否正确
            if(vcu.checkCacheKey(phoneNumber,newCode)){
                String userId=SnowflakeUtil.getID();
                userInfo.setID(userId);
                if(uim.insert(userInfo)>0){
                    ru.set(userId+"_newUser","newUser");
                }



                return CommonResult.success("注册成功");
            }else{
                return CommonResult.fail(CodeEnum.VERIFICATION_CODE_FAILURE);
            }
        }
        return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);
    }

    /**
     * 获取验证码
     * @param phoneNumber
     * @return
     */
    public CommonResult<String> getVerificationCode (String phoneNumber){
        if(StrUtil.isNotBlank(phoneNumber)){
            String code = vcu.put(phoneNumber);
            return CommonResult.success(code);
        }
        return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);
    }

    /**
     * 用户登录
     * @param userInfo
     * @return
     */
   public CommonResult<String> userLogin (UserInformation userInfo){

       if(StrUtil.isNotBlank(userInfo.getNickName())&&StrUtil.isNotBlank(userInfo.getPassword())){
           //判断用户是否存在
           QueryWrapper<UserInformation> queryWrapper=new QueryWrapper<>(userInfo);
           //查询用户信息
           UserInformation userInformation = uim.selectOne(queryWrapper);

           if(userInformation!=null){
               //填充token的payload
               Map<String,String> tokenMap=new HashMap<String,String>(){{
                   put("ID",userInformation.getID());
                   put("nickName",userInformation.getNickName());
                   put("avatarLink",userInformation.getAvatarLink());
               }};
               String token = JWTUtils.getToken(tokenMap);
               //判断是否为新用户登录
               Object newUserStr = ru.get(userInformation.getID()+"_newUser");
               if(newUserStr!=null&&"newUser".equals(newUserStr.toString())){
                   //创建一条留言
                   LeavingAMessage leavingAMessage=new LeavingAMessage();
                   leavingAMessage.setCommenterId(new UserInformation().setID("1"));
                   leavingAMessage.setRecipientId(userInformation);
                   leavingAMessage.setContent("尊敬的"+userInformation.getNickName()+"用户您好，We are meant to be 欢迎您的加入，我们 注定 相遇~");
                   leavingAMessage.setType(0);
                   leavingAMessage.setIsOperation(0);

                   //将留言推送至MQ
                   CommonResult<String> result = messageBoardFeignService.pushLeavingAMessageData(MqMessage.setMessageTypeAndData(leavingAMessage, MqMessage.MESSAGE_TYPE_PRIVATE_LETTER), token);
                  if(result.getCode()==200){
                      //移除当前缓存的新用户标识
                      ru.deleteKey(userInformation.getID());
                  }
                   System.err.println(result);

               }


               return CommonResult.success(token);
           }else {
               //登录失败
               return CommonResult.fail(CodeEnum.LOGIN_FAILED);
           }

       }
       return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);
   }

    /**
     * 获取用户详细信息
     * @param userID
     * @return
     */
    @Override
    public CommonResult<UserInformation> getUserDetailedMsg(String userID) {
        if(StrUtil.isNotBlank(userID)){
            QueryWrapper<UserInformation> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("ID", "avatar_link","nick_name","create_time").eq("ID",userID);
           return  CommonResult.success(uim.selectOne(queryWrapper));
        }
        return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);
    }

    /**
     * 根据用户昵称查询用户列表
     * @param nickName
     * @return
     */
    @Override
    public CommonResult<List<UserInformation>> queryUserListService(String nickName) {
        if(StrUtil.isNotBlank(nickName)){
            QueryWrapper<UserInformation> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("nick_name",nickName);
           return  CommonResult.success(uim.selectList(queryWrapper));
        }
        return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);
    }





}
